package com.dykj.fireFighting.web.onenet.service.impl;

import com.alibaba.fastjson.JSON;
import com.dykj.fireFighting.api.base.emergency.entity.EmergencyStaff;
import com.dykj.fireFighting.api.base.emergency.service.IEmergencyStaffService;
import com.dykj.fireFighting.api.base.news.service.IAliMessageService;
import com.dykj.fireFighting.common.core.constant.WebsocketConstant;
import com.dykj.fireFighting.common.starter.redisson.service.RedisService;
import com.dykj.fireFighting.web.base.websocket.entity.MoreMessage;
import com.dykj.fireFighting.web.model.Device;
import com.dykj.fireFighting.web.model.haiman.HaiManGas;
import com.dykj.fireFighting.web.model.haiman.HaiManSmoke;
import com.dykj.fireFighting.web.model.vo.SocialUnitVo;
import com.dykj.fireFighting.web.onenet.service.HaiManService;
import com.dykj.fireFighting.web.rocketmq.producer.InsertDevHisGasProducer;
import com.dykj.fireFighting.web.rocketmq.producer.InsertDevHisSmokeProducer;
import com.dykj.fireFighting.web.service.DevHisService;
import com.dykj.fireFighting.web.service.SysUserService;
import com.dykj.fireFighting.web.utils.UUIDUtils;
import net.sf.json.JSONObject;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class HaiManServiceImpl implements HaiManService {
    @Autowired
    private RedisService redisService;
    @Autowired
    private DevHisService devHisService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private InsertDevHisSmokeProducer insertDevHisSmokeProducer;
    @Autowired
    private InsertDevHisGasProducer insertDevHisGasProducer;
    @DubboReference
    private IAliMessageService aliMessageService;
    @DubboReference
    private IEmergencyStaffService iEmergencyStaffService;

    @Override
    public void putHaiManSmokeToMQ(Object obj,String name) {
        JSONObject jsonMsg = JSONObject.fromObject(obj);
        //查询设备，有设备继续，无设备return
        String devId = jsonMsg.getString("imei");
        Device device = JSON.parseObject((String) redisService.get(devId), Device.class);
        if (device == null) {
            device = devHisService.queryCreateBy(devId);
        }
        if (device == null) {
            return;
        }
        redisService.set(devId, JSON.toJSONString(device));

        String type = jsonMsg.getString("type");
        if (null == type || Integer.parseInt(type)>2){
            return;
        }

        HaiManSmoke haiManSmoke = new HaiManSmoke();
        SocialUnitVo socialUnitVo = getContacts(device);
        haiManSmoke.setUnitId(device.getUnitId());
        haiManSmoke.setUnitName(device.getUnitName());
        haiManSmoke.setCenterUnitId(socialUnitVo.getCenterUnitId());
        haiManSmoke.setUploadTime(stampToDate(jsonMsg.getString("at")));
        haiManSmoke.setRelationId(device.getRelationId());
        haiManSmoke.setId(UUIDUtils.getTimeUUID());
        haiManSmoke.setDeviceName(device.getName());
        //推送
        MoreMessage moreMessage = new MoreMessage();
        moreMessage.setUserIds(socialUnitVo.getUnitUserIds().toArray(new String[0]));
        moreMessage.setCmd(WebsocketConstant.CMD_TOPIC);
        moreMessage.setMsgId(haiManSmoke.getId());
        //上下线
        if (2 == Integer.parseInt(type)) {
            String status= jsonMsg.getString("status");
            if (status.equals("0")){
                device.setStatus("设备离线");
            }else {
                device.setStatus("设备上线");
            }
            haiManSmoke.setAlarmState(device.getStatus());
            insertDevHisSmokeProducer.asyncSend(haiManSmoke, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("=======发送插入海曼烟感上下线消息成功=======");
                }

                @Override
                public void onException(Throwable throwable) {
                    System.out.println("=======发送插入海曼烟感上下线消息失败=======");
                }
            });
            //上线通知推送
            moreMessage.setMsgTitle("设备上下线通知");
            moreMessage.setMsgTxt(device.getName() + "于" + haiManSmoke.getUploadTime() + device.getStatus());
            redisService.convertAndSend("channel:moreMessage", moreMessage);
            return;
        }


        String str = jsonMsg.getString("value");
        System.out.println(str);
        String substring = str.substring(1, str.length() - 1);
        String[] split = substring.split(",");
        if (split.length>70) {
            double smoke =Double.parseDouble(split[4])/100;
            double wenDu =Double.parseDouble(getStringByStrs(split[9],split[10]).toString())/100;
            String nbDianLiang = split[15]+"%";
            Integer xinHao = getStringByStrs(split[20],split[21])-65536;
            String alarmState = getState(getStringByStrs(split[26],split[27]));
            String wuRan = split[70];
            System.out.println("烟雾浓度："+smoke);
            System.out.println("温度值："+wenDu);
            System.out.println("NB板电量："+nbDianLiang);
            System.out.println("信号强度："+xinHao);
            System.out.println("报警状态："+alarmState);
            System.out.println("迷宫污染度："+wuRan);
            device.setCalculationValue(smoke);
            device.setT(Double.toString(wenDu));
            device.setStatus(alarmState);
            device.setV(nbDianLiang);
            device.setQ(Integer.toString(xinHao));
            //设备的模拟量类型----迷宫污染度（烟感没有模拟量类型，暂用该字段）
            device.setMoniType(wuRan);
            redisService.set(devId+"_realtime", JSON.toJSONString(device));

            haiManSmoke.setAlarmState(device.getStatus());
            haiManSmoke.setWenDu(device.getT());
            haiManSmoke.setNbDianLiang(device.getV());
            haiManSmoke.setXinHao(device.getQ());
            haiManSmoke.setWuRan(device.getMoniType());
            haiManSmoke.setSmoke(Double.toString(device.getCalculationValue()));
            if (!haiManSmoke.getAlarmState().equals("正常")){
                //发送短信
                List<EmergencyStaff> emergencyStaffList;
                emergencyStaffList = getWaterEgencyStaffList(device.getUnitId());
                if (emergencyStaffList.size()>0) {
                    aliMessageService.sendAliMessageBatch(emergencyStaffList, "唐山臻旭科技有限公司", "SMS_213772600", device.getName(), haiManSmoke.getUploadTime(), haiManSmoke.getAlarmState());
                }
                //推送
                moreMessage.setMsgTitle("设备告警通知");
                moreMessage.setMsgTxt(device.getName() + "于" + haiManSmoke.getUploadTime() + device.getStatus());
                redisService.convertAndSend("channel:moreMessage", moreMessage);
            }

            //入库
            insertDevHisSmokeProducer.asyncSend(haiManSmoke, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("=======发送插入海曼烟感数据消息成功=======");
                }

                @Override
                public void onException(Throwable throwable) {
                    System.out.println("=======发送插入海曼烟感数据消息失败=======");
                }
            });

        }

    }

    @Override
    public void putHaiManGasToMQ(Object obj, String name) {
        JSONObject jsonMsg = JSONObject.fromObject(obj);
        //查询设备，有设备继续，无设备return
        String devId = jsonMsg.getString("imei");
        Device device = JSON.parseObject((String) redisService.get(devId), Device.class);
        if (device == null) {
            device = devHisService.queryCreateBy(devId);
        }
        if (device == null) {
            return;
        }
        redisService.set(devId, JSON.toJSONString(device));

        String type = jsonMsg.getString("type");
        if (null == type || Integer.parseInt(type)>2){
            return;
        }
        HaiManGas haiManGas = new HaiManGas();
        SocialUnitVo socialUnitVo = getContacts(device);
        haiManGas.setUnitId(device.getUnitId());
        haiManGas.setUnitName(device.getUnitName());
        haiManGas.setCenterUnitId(socialUnitVo.getCenterUnitId());
        haiManGas.setUploadTime(stampToDate(jsonMsg.getString("at")));
        haiManGas.setRelationId(device.getRelationId());
        haiManGas.setId(UUIDUtils.getTimeUUID());
        haiManGas.setDeviceName(device.getName());
        //推送
        MoreMessage moreMessage = new MoreMessage();
        moreMessage.setUserIds(socialUnitVo.getUnitUserIds().toArray(new String[0]));
        moreMessage.setCmd(WebsocketConstant.CMD_TOPIC);
        moreMessage.setMsgId(haiManGas.getId());
        //上下线
        if (2 == Integer.parseInt(type)) {
            String status= jsonMsg.getString("status");
            if (status.equals("0")){
                device.setStatus("设备离线");
            }else {
                device.setStatus("设备上线");
            }
            haiManGas.setAlarmTypeStr(device.getStatus());
            insertDevHisGasProducer.asyncSend(haiManGas, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("=======发送插入海曼可燃气体上下线消息成功=======");
                }

                @Override
                public void onException(Throwable throwable) {
                    System.out.println("=======发送插入海曼可燃气体上下线消息失败=======");
                }
            });
            //上线通知推送
            moreMessage.setMsgTitle("设备上下线通知");
            moreMessage.setMsgTxt(device.getName() + "于" + haiManGas.getUploadTime() + device.getStatus());
            redisService.convertAndSend("channel:moreMessage", moreMessage);
            return;
        }

        String str = jsonMsg.getString("value");
        System.out.println(str);
        String substring = str.substring(1, str.length() - 1);
        String[] split = substring.split(",");
        if (split.length>70) {
            double gas = Double.parseDouble(getStringByStrs(split[4], split[5]).toString());
            Integer xinHao = getStringByStrs(split[10],split[11])-65536;
            String gasStatus = split[16];
            String gasStatusStr = getGasState(Integer.parseInt(gasStatus));
            String alarmType =split[21];
            String alarmTypeStr = getAlarmType(Integer.parseInt(alarmType));
            String handStatus =split[26];
            String handStatusStr = getHandState(Integer.parseInt(handStatus));
            System.out.println("气体浓度："+gas);
            System.out.println("信号强度："+xinHao);
            System.out.println("气感状态："+gasStatusStr);
            System.out.println("报警类型："+alarmTypeStr);
            System.out.println("机械手状态："+handStatusStr);
            device.setCalculationValue(gas);
            device.setQ(gasStatusStr);
            device.setStatus(alarmTypeStr);
            device.setT(handStatusStr);
            device.setV(Integer.toString(xinHao));
            redisService.set(devId+"_realtime", JSON.toJSONString(device));
            if (alarmTypeStr.equals("正常")&&gasStatusStr.equals("正常")) {
                return;
            }
            haiManGas.setGas(Double.toString(device.getCalculationValue()));
            haiManGas.setGasStatus(gasStatus);
            haiManGas.setGasStatusStr(device.getQ());
            haiManGas.setAlarmType(alarmType);
            haiManGas.setAlarmTypeStr(device.getStatus());
            haiManGas.setHandStatus(handStatus);
            haiManGas.setHandStatusStr(device.getT());
            haiManGas.setXinHao(device.getV());
            if (!haiManGas.getAlarmTypeStr().equals("正常")) {
                //发送短信
                List<EmergencyStaff> emergencyStaffList;
                emergencyStaffList = getWaterEgencyStaffList(device.getUnitId());
                if (emergencyStaffList.size()>0){
                    aliMessageService.sendAliMessageBatch(emergencyStaffList, "唐山臻旭科技有限公司", "SMS_213772600", device.getName(), haiManGas.getUploadTime(), haiManGas.getAlarmTypeStr());
                }

                //推送
                moreMessage.setMsgTitle("可燃气体预警通知");
                moreMessage.setMsgTxt(device.getName() + "于" + haiManGas.getUploadTime() + "发生"+device.getStatus());
                redisService.convertAndSend("channel:moreMessage", moreMessage);
            }
            insertDevHisGasProducer.asyncSend(haiManGas, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("=======发送插入海曼可燃气体消息成功=======");
                }

                @Override
                public void onException(Throwable throwable) {
                    System.out.println("=======发送插入海曼可燃气体消息失败=======");
                }
            });
        }
    }

    private Integer getStringByStrs(String str1,String str2){
        int num1= Integer.parseInt(str1);
        int num2= Integer.parseInt(str2);
        if (num1<0) {
            num1+=256;
        }
        if (num2<0) {
            num2+=256;
        }
        String res1 = Integer.toHexString(num1);
        String res2 = Integer.toHexString(num2);
        if (res1.length() < 2) {
            res1 = "0"+res1;
        }
        if (res2.length() < 2) {
            res2 = "0"+res2;
        }
        return Integer.parseInt(res1+res2,16);
    }
    private String getState(int num){
        String result="";
        switch (num) {
            case 0:
                result="正常";
                break;
            case 1:
                result="烟雾报警";
                break;
            case 2:
                result="烟雾报警解除";
                break;
            case 3:
                result="温度报警";
                break;
            case 4:
                result="温度报警解除";
                break;
            case 5:
                result="烟感低电量报警";
                break;
            case 6:
                result="烟感低电量报警解除";
                break;
            case 7:
                result="NB低电量报警";
                break;
            case 8:
                result="NB低电量报警解除";
                break;
            case 9:
                result="烟雾传感器故障";
                break;
            case 10:
                result="烟雾传感器故障解除";
                break;
            case 11:
                result="温湿度传感器故障";
                break;
            case 12:
                result="温湿度传感器故障解除";
                break;
            case 13:
                result="自检测试开始";
                break;
            case 14:
                result="自检测试完成";
                break;
            case 15:
                result="防拆触发";
                break;
            case 16:
                result="防拆恢复";
                break;
            default:
                result="设备数据错误";
                break;
        }
        return result;
    }

    private String getHandState(int num){
        String result="";
        switch (num) {
            case 0:
                result="关闭";
                break;
            case 1:
                result="打开";
                break;
            case 2:
                result="未连接";
                break;
            case 3:
                result="正在打开";
                break;
            case 4:
                result="正在关闭";
                break;
            case 5:
                result="机械手故障";
                break;
            case 6:
                result="电磁阀关";
                break;
            default:
                result="设备数据错误";
                break;
        }
        return result;
    }

    private String getGasState(int num){
        String result="";
        switch (num) {
            case 0:
                result="正常";
                break;
            case 1:
                result="正在自检";
                break;
            case 2:
                result="正在预热";
                break;
            case 3:
                result="自检成功";
                break;
            case 4:
                result="设备故障";
                break;
            case 5:
                result="预热完成";
                break;
            default:
                result="设备数据错误";
                break;
        }
        return result;
    }

    private String getAlarmType(int num){
        String result="";
        switch (num) {
            case 0:
                result="正常";
                break;
            case 1:
                result="GAS报警恢复";
                break;
            case 2:
                result="GAS轻度泄漏";
                break;
            case 3:
                result="GAS重度泄漏";
                break;
            case 4:
                result="短路故障";
                break;
            case 5:
                result="开路故障";
                break;
            case 6:
                result="机械手故障";
                break;
            case 7:
                result="其他故障";
                break;
            case 8:
                result="自检完成";
                break;
            case 9:
                result="设备断电";
                break;
            case 10:
                result="寿命到期";
                break;
            default:
                result="设备数据错误";
                break;
        }
        return result;
    }

    private SocialUnitVo getContacts(Device device) {
        SocialUnitVo unit = JSON.parseObject((String) redisService.get(device.getRelationId() + "-unit"), SocialUnitVo.class);
        if (null == unit) {
            unit = new SocialUnitVo();
            Map<String, Object> centerUnit = sysUserService.getCenterUnit(device.getUnitId());
            unit.setCenterUnitId(centerUnit.get("id").toString());
            unit.setUnitUserIds(sysUserService.getUserByUnitId(device.getUnitId()));
            unit.setCenterUserIds(sysUserService.getCenterUserByUnitId(device.getUnitId()));

            List<String> idList = sysUserService.getUnitIds(device.getUnitId());
            List<String> centerIds = unit.getCenterUserIds();
            List<String> unitIds = new ArrayList<>();
            for (String centerid : centerIds) {
                for (String unitid : idList) {
                    unitIds.add(centerid + "-" + unitid);
                }
            }
            unit.setUnitIds(unitIds);

            redisService.set(device.getRelationId() + "-unit", JSON.toJSONString(unit));
        }
        return unit;
    }

    public String stampToDate(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
    private List<EmergencyStaff> getWaterEgencyStaffList(String unitId) {
        return iEmergencyStaffService.getWaterStaffByUnitid(unitId);
    }

}
